<?php


namespace App\Services\Result;

use App\Interf\Resultable;
use Monolog\Logger;
use TestingConfig;
use ParamConfig;
use App\Models\LogHelper;


class MentalHealthResult extends BaseResult implements Resultable
{
    private $answers;

    private $summaryObj;


    public function __construct($answersStr = null)
    {
        $this->answers = $this->convertAnswer($answersStr);

        $this->summaryObj = $this->configAttrObj(1,'测评结果');

    }

    public function result()
    {

         $attrs = [];
        array_push($attrs, $this->getSummaryAttr());

        $data['attrs'] = $attrs;
        $data['chatparam'] = $this->getChatparam();
        //图类型常规图
        $data['chatType'] = $this->getChatType();


        return $data;


    }



    public function getSummaryAttr()
    {
        $note='';
        $extra = '';
        $this->getNoteByIndex($note,$this->answers,'31');

        $obj = $this->summaryObj;
        $obj = $this->compactAttrObj($obj['attr_id'], $obj['title'], $note, $extra);

        LogHelper::log($obj);
        return $obj;
    }




    public function getNoteByIndex(&$note,$answers,$index)
   {

       $obj = $this->getAnswerObjByIndex($answers,$index);

        $note .= $this->getItemResult($obj['index'],$obj['weight']);
        $note = str_replace('@31', $this->getChatparam(), $note);
    }




    /**
     * 获取单个问题通过条件判断后最终的结果
     */
    protected function getItemResult($index,$answerWeight){
        $result = '';

        $values = $this->getSingleItemConfig($index);

        if(count($values)>0){
            foreach ($values as $val){
                $expression = $val['key'];
                if($data = $this->getQuestionItemCondResult($expression,$answerWeight)){
                    $result = $val['value'];

                    break;
                }
            }
        }

        return $result;
    }

    /**
     * 图标对应的totalScore
     */
    protected function getChatparam(){

        $answer31 = $this->getAnswerObjByIndex($this->answers,'31');

         $data= $answer31['weight'];

        return $data;
    }


    /**
     * 获取单个题目对应的条件判断值
     */
    protected function getQuestionItemCondResult($expression,$originVal){
        $expression = $expression.'?1:0;';
        $expression = str_replace('@31', $originVal, $expression);
        $result = $this->compactExpress($expression,$originVal);
        return $result;
    }

    /**
     * 组装表达式,这里充分的利用eval函数可以计算的功能
     * @param string $expression 原始表达式
     * @param string $orgVal 原始值
     * @return string
     */
    protected function compactExpress($expression, $orgVal){
        $val = '$val='.$expression;
        eval($val);
        return $val;
    }


    /**
     * 获取单个题目对应的配置信息
     */
    protected function getSingleItemConfig($index){
        $values = ParamConfig::getMentalHealthTestingNoteByTag($index);
        return $values;
    }





}